<?php
//+-------------------------------------------------------------
//| 前端app控制器基类
//+-------------------------------------------------------------
//| Author Liu LianSen <liansen@d3zz.com> 
//+-------------------------------------------------------------
//| Date 2017-09-06
//+-------------------------------------------------------------
namespace app\common\controller;

use app\appclient\Error;
use app\sys\model\SysUser;
use think\Exception;
use think\response\Json;
use traits\ExceptionResult;
use traits\HttpResponse;

/**
 *
 *
 * @author Liu LianSen <liansen@d3zz.com>
 * @since 2017-09-06
 */
class AppController extends \think\Controller
{
   const MODULE_NAME = 'credit';
   use HttpResponse;
   use ExceptionResult;

    /**
     * 获取data字段参数
     * @return mixed
     */
   protected function getRequestData()
   {
       try{
            return $this->request->param('data/a');
       }catch (\Exception $e){
            $res = new Json([
                'status'  => Error::BAD_REQUEST_CODE,
                'message' => Error::DATA_CANNOT_RECOVER_JSON,
                'data'    => []
            ]);
            $res->send();
       }
   }


    /**
     * 获取data参数中的值
     * @param string $key
     * @param string $default
     * @return mixed|string
     */
   public function get($key = '',$default = null)
   {
       $data = $this->getRequestData();
       if($key){
           return isset($data[$key]) ? $data[$key] : $default;
       }
       return $data;
   }

    /**
     * @return mixed|string
     * @throws Exception
     */
   public function getToken()
   {
       $token = $this->get('token');
       if(!$token){
           throw new Exception(Error::NOT_SET_TOKEN_MSG,Error::BAD_REQUEST_CODE);
       }
       return $token;
   }



    /**
     * 获取token对应的用户
     * @param array $width
     * @param bool $cache
     * @return SysUser
     * @throws Exception
     */
    public function getTokenUser($width = [],$cache = false)
    {
        $user = SysUser::get(['token' => $this->getToken()], $width, $cache);
        if(!$user){
            throw new Exception(Error::TOKEN_INVALID_MSG,Error::NOT_FOUND_CODE);
        }
        return $user;
    }


    /**
     * 获取当前请求用户<br/>
     * 前提是data中存在token参数
     * @return SysUser|null
     */
    public function getCurrentUser(){
        return isset($this->request->user) ? $this->request->user:null;
    }


    /**
     * 获取请求参数
     * @return array|null
     */
    public function getParam(){
        $param = $this->request->param();
        return isset($param) ? $param : null;
    }


}
